<template>
	<view>
		<y-chat :userId="userId" :messageList="msgList" :updateList="updateList" 
			:tagOptions="tagOptions" :useRefresh="false" @send="sendMsg"></y-chat>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				//当前用户的ID
				userId: this.$.getUserInfo().uid,
				//好友的信息
				friendInfo: {},
				//消息列表
				msgList: [],
				updateList: null,
				//标签的列表
				tagOptions: {
					
				}
			}
		},
		onLoad(p) {
			//获取好友的基本信息
			this.friendInfo = JSON.parse(p.friendInfo);
			
			//修改聊天页面的标题栏
			uni.setNavigationBarTitle({
				title: this.friendInfo.name
			});
			
			//读取缓存，将消息展示
			this.readCacheMsg();
			
			//注册一个WebSocket消息接收的事件
			//messageget_1_5
			uni.$on('messageget_' + this.userId + "_" + this.friendInfo.id, (msgObj) => {
				// console.log('监听到事件来自 messageget_' + this.userId + '_' + this.friendInfo.id + '，携带参数 msg 为：', msg);
				var msg = this.ws.createShowMsg(msgObj.from, msgObj.msg, 1);
				//展示到页面上
				this.updateList = msg;
			});
			
			//发送清空标记的事件
			uni.$emit("clearNum", this.friendInfo.id);
		},
		onUnload() {
			//页面卸载的方法
			uni.$off('messageget_' + this.userId + "_" + this.friendInfo.id);
			//发送清空标记的事件
			uni.$emit("clearNum", this.friendInfo.id);
		},
		methods: {
			//发送消息
			sendMsg(content){
				//构建一个消息对象
				var msg = this.ws.createShowMsg(this.userId, content, 1);
				//展示到页面上
				this.updateList = msg;
				//将消息缓存
				this.ws.setMsgCache(this.userId, this.friendInfo.id, msg);
				
				
				//将消息发送给WebSocket服务器
				var msgObj = {
					action: 101,
					from: this.userId,
					to: this.friendInfo.id,
					msg: content
				}			
				this.ws.sendWsMsg(msgObj);
				//将私聊消息转发给消息页面
				uni.$emit('messagelist', msgObj);
			},
			//读取缓存的消息
			readCacheMsg(){
				var msgArray = this.ws.getMsgCache(this.userId, this.friendInfo.id);
				console.log(this.userId + "  " + this.friendInfo.id + "读取到缓存：", msgArray);
				if(msgArray){
					//有缓存,显示缓存的内容，要延迟一段时间
					setTimeout(() => {
						this.msgList = msgArray;
					}, 100);
				}
			}
		}
	}
</script>

<style>

</style>
